import config from "./config";
let pending: any = []; //请求中的接口
let isRefresh = false; //正在刷新
let ref = false; //判断token是否过期
let times = 0; //判断获取token接口请求的次数
function sendRequest(params: any, baseUrl: any = config.baseUrl) {
  if (ref) {
    if (!isRefresh) {
      isRefresh = true;
      getToken();
    }
    return new Promise((resolve, reject) => {
      pending.push((isSuccess: any) => {
        if (isSuccess) {
          resolve(sendRequest(params, baseUrl));
        } else {
          //token失效处理
          times = 0;
          resolve({
            message: "token失效",
            code: 502,
            data: {},
          });
          uni.setStorage({
            key: "token",
            data: "",
            success: () => {
              uni.showToast({
                title: "登录过期，请重新登录",
                icon: "none",
              });
              // setTimeout(() => {
              //   uni.switchTab({
              //     url: "/pages/member/index/index",
              //   });
              // }, 1000);
            },
          });
        }
      });
    });
  }
  let method = params.type || "GET";
  let url: any;
  url = baseUrl + params.url;
  let req = new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: method,
      data: params.data,
      header: params.header || {
        "Content-Type": "application/json",
        token: uni.getStorageSync("token") || "",
      },
      dataType: params.dataType || "json",
      responseType: params.responseType || "text",
      success: (res) => {
        resolve(res.data);
      },
      fail: (res) => {
        reject(res);
      },
      complete: (res) => {
        reject(res);
      },
    });
  });
  let timer: any;
  let timeout = new Promise((res, rej) => {
    timer = setTimeout(() => {
      res({
        message: "服务器请求超时，请稍后再试~",
        code: 500,
      });
    }, 10000);
  });
  return Promise.race([req, timeout])
    .then((res: any) => {
      if (res.code === 1005) {
        ref = true;
        return sendRequest(params, baseUrl);
      }
      if (timer) {
        clearTimeout(timer);
      }
      return res;
    })
    .catch((rej) => {
      console.log(rej);
    });
}
/**
 * 刷新token
 */
function getToken() {
  times++;
  if (times >= 3) {
    handler(false);

    return;
  }
  uni.request({
    url: `${config.baseUrl}/vapi/login/refreshToken`,
    method: "GET",
    header: {
      "content-type": "application/x-www-form-urlencoded;application/json",
      token: uni.getStorageSync("token"),
    },
    dataType: "json",
    responseType: "text",
    success: (res: any) => {
      if (res.data.code == 200) {
        uni.setStorage({
          key: "token",
          data: res.data.data.token,
          success: () => {
            handler(true);
          },
        });
      } else {
        handler(false);
      }
    },
    fail: () => {
      handler(false);
    },
  });
}
/**
 * token刷新处理pending中的函数
 * @param {*} res true:处理成功 false:处理失败
 */
function handler(res: any) {
  isRefresh = false;
  ref = false;
  pending.forEach((callback: any) => {
    callback(res);
  });
  pending = [];
}
export default { sendRequest };
